/*
 * @Author: sx
 * @Date: 2021-10-22 18:25:36
 * @Last Modified by:   lt
 * @Last Modified time: 2021-10-27 15:37:14
 */
import type { MenuDataItem } from '@ant-design/pro-layout';

const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

/**
 * 存储token
 * @param token
 */
export function setToken(token: string) {
  localStorage.setItem('token', token);
}
/**
 * 获取token
 */
export const getToken = () => {
  return localStorage.getItem('token') || 'token';
};

/**
 * 清除token
 */
export const removeToken = () => {
  localStorage.removeItem('token');
};

/**
 *
 * 获取请求地址
 */
export const serverUrl = () => {
  // 开发环境
  switch (REACT_APP_ENV) {
    case 'dev':
      return 'http://192.168.1.191:10002';

    case 'prod':
      return 'https://court.yneusoft.com/pcManager';

    default:
      return 'http://127.0.0.1:8805';
  }
};

/**
 * 处理图片地址
 * @param url
 */
export const resetImagUrl = (url: string) => {
  return url.startsWith('http') ? url : serverUrl + url;
};

/**
 * 转换select需要的数据格式
 * @param data 数据源
 * @param valueString value字段
 * @param hasStop 是否有禁用/启用
 */
export const changeSelectData = (data: any, valueString: string, hasStop?: boolean) => {
  return (
    data?.map((item: any) => {
      return {
        label: item.name,
        value: valueString === 'aid' ? item.aid : item.id,
        disabled: hasStop ? item.isStop : false,
      };
    }) || []
  );
};

export const handleMenu = (
  menuData: MenuDataItem[],
  powerData: { id: number; name: string }[],
): MenuDataItem[] => {
  const resultMenu: MenuDataItem[] = [];
  menuData.forEach((menuItem: MenuDataItem) => {
    const hasPower = powerData.some((item) => item.id === menuItem.id);
    if (!menuItem.hasOwnProperty('id') || hasPower) {
      const children = handleMenu(menuItem.children || [], powerData);
      const hasChildRoute = children?.some(
        (item) => typeof item.hideInMenu === 'undefined' || !item.hideInMenu,
      );
      if ((hasChildRoute || menuItem.component) && !menuItem.hasOwnProperty('redirect')) {
        const name = hasPower
          ? powerData.find((item) => item.id === menuItem.id)?.name
          : menuItem.name;
        resultMenu.push({
          ...menuItem,
          name,
          children,
        });
      }
    }
  });
  return resultMenu;
};

/**
 * 时间格式转换
 * @param obj {Date} 时间对象或字符串
 * @param dateType {Number} 返回时间的型， 0：返回年份，1：返回年月，2：返回年月日
 * @return {String} 返回yy-MM-dd格式时间字符串
 */
export const formatDate = (obj: Date | string, dateType: 0 | 1 | 2 = 2) => {
  if (!obj) return '';
  const time = new Date(obj);
  const year = time.getFullYear();
  const month = `0${time.getMonth() + 1}`;
  const date = `0${time.getDate()}`;

  if (dateType || dateType === 0) {
    switch (dateType) {
      case 0:
        return `${year}`;
      case 1:
        return `${year}-${month.substring(month.length - 2, month.length)}`;
      case 2:
        return `${year}-${month.substring(month.length - 2, month.length)}-${date.substring(
          date.length - 2,
          date.length,
        )}`;
      default:
        return `${year}-${month.substring(month.length - 2, month.length)}-${date.substring(
          date.length - 2,
          date.length,
        )}`;
    }
  } else {
    return `${year}-${month.substring(month.length - 2, month.length)}-${date.substring(
      date.length - 2,
      date.length,
    )}`;
  }
};
